<template>
  <el-dialog :title="$t('table.update')" width="760px" :visible="true" @close="onClose" top="5vh">
    <el-form :model="form" :rules="rules" ref="dialog-form" label-width="85px" size="small">
      <el-row :gutter="5">
        <el-col :span="12">
          <el-form-item :label="$t('user.username')" prop="username">
            <el-input v-model="form.username" readonly></el-input>
          </el-form-item>
          <el-form-item :label="$t('user.fullName')" prop="fullName">
            <el-input v-model="form.fullName"></el-input>
          </el-form-item>
          <el-form-item :label="$t('user.birthday')" prop="birthday">
            <el-date-picker v-model="form.birthday" type="date" placeholder="选择日期" style="width: 100%;" :editable="false"></el-date-picker>
          </el-form-item>
          <el-form-item :label="$t('user.group')" prop="group">
            <el-select v-model="form.group" value-key="id" clearable placeholder="请选择" style="width: 100%;" @change="onGroupChange">
              <el-option v-for="item in groups" :key="item.id" :label="item.name" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('user.region')" prop="regionCode">
            <el-cascader size="small" :options="addressData" v-model="region" @change="onRegionChange" style="width: 100%;">
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('user.avatar')">
            <div class="thumb-container" @click="imagecropperShow = true">
              <img :src="form.avatar" class="thumb">
            </div>
          </el-form-item>
          <el-form-item :label="$t('user.enabled')" prop="enabled">
            <el-radio v-model="form.enabled" label="true">{{$t('user.enum.enabled.true')}}</el-radio>
            <el-radio v-model="form.enabled" label="false">{{$t('user.enum.enabled.false')}}</el-radio>
          </el-form-item>
          <el-form-item :label="$t('user.sex')" prop="sex">
            <el-radio v-model="form.sex" label="M">{{$t('user.enum.sex.M')}}</el-radio>
            <el-radio v-model="form.sex" label="F">{{$t('user.enum.sex.F')}}</el-radio>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item :label="$t('user.street')" prop="street">
        <el-input v-model="form.street"></el-input>
      </el-form-item>
      <el-form-item :label="$t('user.org')">
        <el-tree :data="orgTree" node-key="id" :props="{'label':'name'}" :expand-on-click-node="false">
          <div slot-scope="{ node, data }" style="width: 100%;">
            <div style="width: 100%;">
              <span>
                {{ node.label}}
              </span>
              <div style="float: right;">
                <el-checkbox v-model="node.data.join" @change="onJoinChange(node)">{{$t('user.join')}}</el-checkbox>
                <span v-show="node.data.join" style="margin-left: 10px;">
                  <el-checkbox v-model="node.data.leader">{{$t('user.leader')}}</el-checkbox>
                  <el-select value-key="code" v-model="node.data.job" :placeholder="$t('user.job')" size="mini" filterable clearable style="margin-left: 10px;">
                    <el-option
                      v-for="item in jobs"
                      :key="item.id"
                      :label="item.text"
                      :value="item">
                    </el-option>
                  </el-select>
                </span>
              </div>
            </div>
            <div v-show="node.data.join && (form.group==null || form.group.autoAuth=='0')" style="width: 100%;">
              <el-select value-key="id" v-model="node.data.selectedRoles" :placeholder="$t('user.roles')" multiple size="mini" filterable clearable style="width: 100%;">
                <el-option
                  v-for="item in node.data.roles"
                  :key="item.id"
                  :label="item.name"
                  :value="item">
                </el-option>
              </el-select>
            </div>
          </div>
        </el-tree>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onClose">{{$t('dialog.cancel')}}</el-button>
      <el-button type="primary" @click="save">{{$t('dialog.save')}}</el-button>
    </div>
    <image-cropper :width="200" :height="200" :maxSize="50" :noRotate="false" @close='closeImagecropper' @crop-success="cropSuccess" v-show="imagecropperShow"></image-cropper>
  </el-dialog>
</template>

<style>
  .thumb-container {
    width: 155px;
    height: 155px;
    border-radius: 50%;
    display: inline-block;
    position: relative;
    cursor: default;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
    text-align: center;
    vertical-align: middle;
  }
  .thumb {
    width: 100%;
    height: 100%;
    background-size: 100%;
    border-radius: 50%;
    overflow: hidden;
    position: relative;
    transform-origin: 95% 40%;
    transition: all 0.3s ease-in-out;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
  }
  .el-tree-node__content {
    min-height: 37px;
    height: inherit;
  }
</style>

<script>
  import Vue from 'vue'
  import { vsprintf } from 'sprintf-js/dist/sprintf.min.js'
  import { regionData, CodeToText } from 'element-china-area-data'
  import { updateToSubmit } from '@/utils/utils'
  import { fetchQuery, fetchGet } from '@/api/restful'
  import ImageCropper from '@/components/ImageCropper'
  import { Loading } from 'element-ui'

  export default {
    components: { ImageCropper },
    data() {
      return {
        imagecropperShow: false,
        form: {avatar:''},
        addressData: regionData,
        region: [],
        groups: [],
        roles: [],
        rules:{
          group:[
            { required: true, message:this.$t('rules.message.required'), trigger: 'blur' },
          ],
          fullName:[
            { required: true, message:this.$t('rules.message.required'), trigger: 'blur' },
            { max: 20, message: vsprintf(this.$t('rules.message.maxLen'), 20), trigger: 'blur' }
          ],
          birthday:[
            { required: true, message:this.$t('rules.message.required'), trigger: 'blur' },
          ],
          regionCode:[
            { required: true, message:this.$t('rules.message.required'), trigger: 'blur' },
            { max: 6, message: vsprintf(this.$t('rules.message.maxLen'), 6), trigger: 'blur' }
          ],
          street:[
            { required: true, message:this.$t('rules.message.required'), trigger: 'blur' },
            { max: 50, message: vsprintf(this.$t('rules.message.maxLen'), 50), trigger: 'blur' }
          ]
        },
        orgTree: [],
        jobs:[]
      };
    },
    methods: {
      save(){
        this.form.fullAddress = this.form.regionName +' '+ this.form.street;
        this.getOrgTreeJoinNodes();
        updateToSubmit.apply(this, [this.form])
      },
      onClose(){
        this.$router.push("/");
      },
      onRegionChange(val){
        if(val.length==3){
          this.form.regionCode = val[2];
          this.form.regionName = CodeToText[val[0]]+'/'+CodeToText[val[1]]+'/'+CodeToText[val[2]];
        }
      },
      closeImagecropper(){
        this.imagecropperShow = false;
      },
      cropSuccess(createImgUrl, field, ki){
        this.imagecropperShow = false;
        this.form.avatar = createImgUrl;
      },
      loadOrgTree(){
        fetchQuery('/org/queryByUser', {'authCode': 'USER'}).then(response => {
          if (response.data.success) {
            var rows = response.data.result;
            for(let i = 0; i < rows.length; i++){
              rows[i].roles = [];
              rows[i].selectedRoles = [];
            }
            var roots = getRoots(rows);
            for (let i = 0; i < roots.length; i++) {
              roots[i].children = getChildren(rows, roots[i].id);
              Vue.set(this.orgTree, i, roots[i]);
            }
            //组织树赋值
            for(let i=0; i<this.form.orgUsers.length; i++){
              let ou = this.form.orgUsers[i];
              let node = this.getOrgTreeNodeById(ou.orgId);
              this.$set(node, 'join', true);
              this.$set(node, 'job', {code: ou.jobCode, text: ou.jobName});
              this.$set(node, 'leader', ou.leader);
              this.loadRoles(node);
              let selectedRoles = [];
              this.form.roles.forEach((role,index) => {
                if(role.org.id == ou.orgId){
                  selectedRoles.push(role);
                }
              });
              this.$set(node, 'selectedRoles', selectedRoles);
            }
          }
        });

        function getRoots(rows) {
          var roots = [];
          for (let i = 0; i < rows.length; i++) {
            let row = rows[i];
            if (row.parent == null || row.parent.id == 0) {
              roots.push(row);
            }
            else{
              let isChild = false;
              for(let j = 0; j<rows.length; j++){
                if(row.parent.id==rows[j].id){
                  isChild = true;
                  break;
                }
              }
              if(!isChild){
                roots.push(row);
              }
            }
          }
          return roots;
        }

        function getChildren(rows, pid) {
          var children = [];
          for (let i = 0; i < rows.length; i++) {
            let row = rows[i];
            if (row.parent != null && row.parent.id == pid) {
              children.push(row);
              row.children = getChildren(rows, row.id);
            }
          }
          return children;
        }
      },
      getOrgTreeJoinNodes(nodes){
        if(nodes){
          for(let i=0; i<nodes.length; i++){
            let node = nodes[i];
            if(node.join && node.job){
              this.form.orgUsers.push({orgId: node.id, orgName: node.name, jobName: node.job.text, jobCode: node.job.code, leader: node.leader});
              if(node.selectedRoles && node.selectedRoles.length>0)
                this.form.roles.push(...node.selectedRoles);
            }
            if(node.children && node.children.length>0){
              this.getOrgTreeJoinNodes(node.children)
            }
          }
        }
        else{
          this.form.orgUsers = [];
          this.form.roles = [];
          for(let i=0; i<this.orgTree.length; i++){
            let node = this.orgTree[i];
            if(node.join && node.job){
              this.form.orgUsers.push({orgId: node.id, orgName: node.name, jobName: node.job.text, jobCode: node.job.code, leader: node.leader});
              if(node.selectedRoles && node.selectedRoles.length>0)
                this.form.roles.push(...node.selectedRoles);
            }
            if(node.children && node.children.length>0){
              this.getOrgTreeJoinNodes(node.children)
            }
          }
        }
      },
      getOrgTreeNodeById(id, nodes){
        if(nodes){
          for(let i=0; i<nodes.length; i++){
            let n = nodes[i];
            if(n.id == id){
                return n;
            }
            else if(n.children && n.children.length>0){
              let res = this.getOrgTreeNodeById(id, n.children);
              if(res){
                  return res;
              }
            }
          }
        }
        else{
          for(let i=0; i<this.orgTree.length; i++){
            let n = this.orgTree[i];
            if(n.id == id){
              return n;
            }
            else if(n.children && n.children.length>0){
              let res = this.getOrgTreeNodeById(id, n.children);
              if(res){
                return res;
              }
            }
          }
        }
      },
      loadRoles(data){
        if(data.roles.length>0){
          data.roles.splice(0, data.roles.length);
        }
        if(data.selectedRoles.length>0){
          data.selectedRoles.splice(0, data.selectedRoles.length);
        }
        if(this.form.group && this.form.group.id && this.form.group.autoAuth=='0'){
          fetchQuery('/role/query',{orgId: data.id, groupId: this.form.group.id}).then( response => {
            if(response.data.success){
              for(var i=0; i<response.data.result.length; i++) {
                Vue.set(data.roles, i, response.data.result[i]);
              }
            }
          });
        }
      },
      reloadRoles(nodes){
        if(nodes){
          for(let i=0; i<nodes.length; i++){
            let node = nodes[i];
            if(node.join){
              this.loadRoles(node);
            }
            if(node.children && node.children.length>0){
              this.reloadRoles(node.children);
            }
          }
        }
        else{
          for(let i=0; i<this.orgTree.length; i++){
            let node = this.orgTree[i];
            if(node.join){
              this.loadRoles(node);
            }
            if(node.children && node.children.length>0){
              this.reloadRoles(node.children);
            }
          }
        }
      },
      onJoinChange(node){
        if(node.data.join){
          this.loadRoles(node.data);
        }
      },
      onGroupChange(){
        this.reloadRoles();
      }
    },
    mounted(){
      let loading = Loading.service({ target: this.$el.childNodes[0] });
      fetchGet('/user/'+this.$parent.selectedRow.id).then(response => {
        if(response.data.success){
          var user = response.data.result;
          var regionCode = user.regionCode;
          if(regionCode){
            var region = [regionCode.substring(0, 2)+'0000', regionCode.substring(0, 4)+'00', regionCode];
            user.regionName = CodeToText[region[0]]+'/'+CodeToText[region[1]]+'/'+CodeToText[region[2]];
            Vue.set(this.region, 0, region[0]);
            Vue.set(this.region, 1, region[1]);
            Vue.set(this.region, 2, region[2]);
          }
          this.form = user;
          //加载组织树
          this.loadOrgTree();
        }
        loading.close();
      }).catch(() => {
        loading.close();
      });
      fetchQuery('/dict/query',{type: 'JOB'}).then( response => {
        if(response.data.success){
          for(var i=0; i<response.data.result.length; i++) {
            Vue.set(this.jobs, i, response.data.result[i]);
          }
        }
      });
      fetchQuery('/userGroup/queryByUser',{}).then( response => {
        if(response.data.success){
          for(var i=0; i<response.data.result.length; i++) {
            Vue.set(this.groups, i, response.data.result[i]);
          }
        }
      });
    }
  };
</script>
